package com.fastDFS;

import com.anniweiya.fastdfs.FastDFSTemplateFactory;
import com.anniweiya.fastdfs.FastDfsInfo;
import com.anniweiya.fastdfs.exception.FastDFSException;
import com.anniweiya.fastdfs.pool.ConnectionPoolFactory;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * com.cimr.icloud.common.fastDFS
 *
 * @Auther: caiming
 * @Date: 2018/10/31 10:06
 * @Description:
 */
public class FastDFSTemplate {
    private ConnectionPoolFactory connPoolFactory;
    private FastDFSTemplateFactory factory;

    public FastDFSTemplate(FastDFSTemplateFactory factory) {
        this.connPoolFactory = new ConnectionPoolFactory(factory);
        this.factory = factory;
    }

    public String uploadAppenderFile(String groupName, byte[] fileBuffer, String fileExtName, NameValuePair[] meta_list) throws FastDFSException {
        StorageClient client = this.getClient();
        String remoteFileName;
        try {
            String[] uploadResults = client.upload_appender_file(groupName, fileBuffer, fileExtName, meta_list);
            remoteFileName = uploadResults[0] + "/" + uploadResults[1];
        } catch (Exception var14) {
            throw new FastDFSException(var14.getMessage(), var14, 0);
        } finally {
            this.releaseClient(client);
        }

        return remoteFileName;

    }

    public int append_file(String remoteFileName, byte[] file_buff) throws FastDFSException {
        StorageClient client = this.getClient();

        int pos = remoteFileName.indexOf("/");
        String[] parts = new String[2];
        if (pos > 0 && pos != remoteFileName.length() - 1) {
            parts[0] = remoteFileName.substring(0, pos);
            parts[1] = remoteFileName.substring(pos + 1);
        }
        try {
            int size = client.append_file(parts[0], parts[1], file_buff);
            return size;
        } catch (Exception var14) {
            throw new FastDFSException(var14.getMessage(), var14, 0);
        } finally {
            this.releaseClient(client);
        }

    }

    public FastDfsInfo upload(byte[] data, String ext) throws FastDFSException {
        return this.upload(data, ext, (Map) null);
    }

    public String upload(String groupName, byte[] data, String ext, NameValuePair[] valuePairs) throws FastDFSException {
        StorageClient client = this.getClient();

        String remoteFileName;
        try {
            String[] uploadResults = client.upload_file(groupName, data, ext, valuePairs);
            remoteFileName = uploadResults[0] + "/" + uploadResults[1];
        } catch (Exception var14) {
            throw new FastDFSException(var14.getMessage(), var14, 0);
        } finally {
            this.releaseClient(client);
        }

        return remoteFileName;
    }

    public FastDfsInfo upload(byte[] data, String ext, Map<String, String> values) throws FastDFSException {
        NameValuePair[] valuePairs = null;
        if (values != null && !values.isEmpty()) {
            valuePairs = new NameValuePair[values.size()];
            int index = 0;

            for (Iterator var6 = values.entrySet().iterator(); var6.hasNext(); ++index) {
                Map.Entry<String, String> entry = (Map.Entry) var6.next();
                valuePairs[index] = new NameValuePair((String) entry.getKey(), (String) entry.getValue());
            }
        }

        StorageClient client = this.getClient();

        FastDfsInfo var10;
        try {
            String[] uploadResults = client.upload_file(data, ext, valuePairs);
            String groupName = uploadResults[0];
            String remoteFileName = uploadResults[1];
            FastDfsInfo fastDfsInfo = new FastDfsInfo(groupName, remoteFileName);
            if (this.factory != null) {
                this.setFileAbsolutePath(fastDfsInfo);
            }

            var10 = fastDfsInfo;
        } catch (Exception var14) {
            throw new FastDFSException(var14.getMessage(), var14, 0);
        } finally {
            this.releaseClient(client);
        }

        return var10;
    }

    public byte[] loadFile(FastDfsInfo dfs) throws FastDFSException {
        return this.loadFile(dfs.getGroup(), dfs.getPath());
    }

    public byte[] loadFile(String remoteFileName) throws FastDFSException {
        StorageClient client = this.getClient();

        int pos = remoteFileName.indexOf("/");
        String[] parts = new String[2];
        if (pos > 0 && pos != remoteFileName.length() - 1) {
            parts[0] = remoteFileName.substring(0, pos);
            parts[1] = remoteFileName.substring(pos + 1);
        }
        byte[] var4;
        try {
            var4 = client.download_file(parts[0], parts[1]);
        } catch (Exception var8) {
            throw new FastDFSException(var8.getMessage(), var8, 0);
        } finally {
            this.releaseClient(client);
        }

        return var4;
    }

    public byte[] loadFile(String groupName, String remoteFileName) throws FastDFSException {
        StorageClient client = this.getClient();

        byte[] var4;
        try {
            var4 = client.download_file(groupName, remoteFileName);
        } catch (Exception var8) {
            throw new FastDFSException(var8.getMessage(), var8, 0);
        } finally {
            this.releaseClient(client);
        }

        return var4;
    }

    public void deleteFile(FastDfsInfo dfs) throws FastDFSException {
        this.deleteFile(dfs.getGroup(), dfs.getPath());
    }

    public void deleteFile(String remoteFileName) throws FastDFSException {
        StorageClient client = this.getClient();
        int pos = remoteFileName.indexOf("/");
        String[] parts = new String[2];
        if (pos > 0 && pos != remoteFileName.length() - 1) {
            parts[0] = remoteFileName.substring(0, pos);
            parts[1] = remoteFileName.substring(pos + 1);
        }
        int code;
        try {
            code = client.delete_file(parts[0], parts[1]);
        } catch (Exception var9) {
            throw new FastDFSException(var9.getMessage(), var9, 0);
        } finally {
            this.releaseClient(client);
        }

        if (code != 0) {
            throw new FastDFSException(code);
        }
    }

    public void deleteFile(String groupName, String remoteFileName) throws FastDFSException {
        StorageClient client = this.getClient();

        int code;
        try {
            code = client.delete_file(groupName, remoteFileName);
        } catch (Exception var9) {
            throw new FastDFSException(var9.getMessage(), var9, 0);
        } finally {
            this.releaseClient(client);
        }

        if (code != 0) {
            throw new FastDFSException(code);
        }
    }

    public String setFileAbsolutePath(String group, String path) throws IOException, NoSuchAlgorithmException, MyException {
        int ts = (int) (System.currentTimeMillis() / 1000L);
        String token = "";
        if (this.factory.isG_anti_steal_token()) {
            token = ProtoCommon.getToken(path, ts, this.factory.getG_secret_key());
            token = "?token=" + token + "&ts=" + ts;
        }

        List addressList;
        if (this.factory.getNginx_address() != null) {
            addressList = this.factory.getNginx_address();
        } else {
            addressList = this.factory.getTracker_servers();
        }

        Random random = new Random();
        int i = random.nextInt(addressList.size());
        String[] split = ((String) addressList.get(i)).split(":", 2);
        int port;
        if (split.length > 1) {
            port = Integer.parseInt(split[1].trim());
        } else {
            port = this.factory.getG_tracker_http_port();
        }

        String address = split[0].trim();
        return this.factory.getProtocol() + address + ":" + port + this.factory.getSepapator() + group + this.factory.getSepapator() + path + token;
    }

    public void setFileAbsolutePath(FastDfsInfo fastDfsInfo) throws IOException, NoSuchAlgorithmException, MyException {
        fastDfsInfo.setFileAbsolutePath(this.setFileAbsolutePath(fastDfsInfo.getGroup(), fastDfsInfo.getPath()));
    }


    protected StorageClient getClient() {
        StorageClient client = null;

        while (client == null) {
            try {
                client = this.connPoolFactory.getClient();
            } catch (Exception var3) {
                var3.printStackTrace();
            }
        }

        return client;
    }

    protected void releaseClient(StorageClient client) {
        this.connPoolFactory.releaseConnection(client);
    }
}
